<template>
	<el-container>
		<el-row :gutter="state.pageInfo.attrs?.gutter" :style="state.pageInfo.attrs?.customStyle || {}" style="width: 100%; overflow: hidden">
			<el-form :model="state.pageData" v-bind="state.pageInfo.attrs" style="width: 100%" ref="formRef">
				<CustomizePageForm
					v-if="state.isReady"
					:page-info="state.pageInfo"
					:cpns="state.pageInfo.components?.getTree()"
					:pageid="pageid"
					:pageData="state.pageData"
					:input-data="inputData"
					:global-data="state.globalData"
					@handleEmitEvent="handleEmitEvent"
					@setFormData="setFormData"
					@clone="clone"
					@updateFormData="updateFormData"
					v-bind="state.styleClass"
					:formRef="formRef"
				/>
			</el-form>
		</el-row>
		<LxDialog v-model="state.dialogVisible" :dialogConfig="dialogConfig" :inputData="copyPageParams" @handleEmitEvent="handleEmitEvent" />
		<!-- <el-button class="clear" @click="clear">清空</el-button> -->
	</el-container>
</template>

<script lang="ts">
import Pages from '../CustomCommon/pages.js';
import Controller from '../CustomCommon/lxy_page_event_combination.js';
import Datar from '../CustomCommon/lxy_params_mgr.js';
import localforage from 'localforage';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import CustomizePageForm from '../CustomizePageForm/index.vue';
import { FormInstance } from 'element-plus';
// const props = withDefaults(defineProps<{ pageid: number; inputData?: Record<string, any> }>(), { inputData: () => ({}), pageid: 0 });
export default defineComponent({
	name: 'custompage',
	components: { CustomizePageForm, LxDialog: defineAsyncComponent(() => import('../../element/lx-dialog.vue')) },
	props: {
		pageid: { type: Number, default: 0 },
		inputData: { type: Object, default: () => ({}) },
	},
	emits: ['queryData', 'clone', 'handleEmitEvent'],
	setup(props, ctx) {
		const proxy = getCurrentInstance()?.proxy;
		// 获取页面信息
		const router = useRouter();
		const state = reactive<{
			pageInfo: Record<string, any>;
			pageData: Record<string, any>;
			globalData: Record<string, any>;
			styleClass: Record<string, any>;
			collectedUp: any[];
			isReady: boolean;
			dialogVisible: boolean;
		}>({
			pageInfo: {},
			pageData: {},
			globalData: {},
			isReady: false,
			styleClass: {},
			collectedUp: [],
			dialogVisible: false,
		});
		const formRef = ref<FormInstance>();
		const dialogConfig = ref();
		const { pageInfo, pageData, isReady, globalData, collectedUp, dialogVisible } = toRefs(state);
		const attrs: Record<string, any> = useAttrs();
		console.log('[Debug][CustomPage]PageID: ', props.pageid);
		console.log('pageInfo', pageInfo);
		const size = {
			medium: 'large',
			small: 'default',
			mini: 'small',
		};
		init();
		async function init() {
			pageInfo.value = await Pages.instance().getPage(props.pageid);
			pageInfo.value.attrs.size = size[pageInfo.value.attrs.size];
			console.log('[Debug][CustomPage]inputData: ', props.inputData);
			if (!pageInfo.value) {
				// 没有查询到页面
				ElMessage({
					message: '页面错误，ErrorCode: 880320',
					type: 'error',
					duration: BASE_API.MSG_SHOW_TIME,
				});
				// 退回到上一个页面。
				router.back();
			} else {
				console.log('[Debug][CustomPage]Page define: ', props.pageid, pageInfo.value, pageInfo.value?.components.cpns);
				// 将页面的输入参数同时拷贝一份为表单对应属性值
				let inputCopy = {};
				if (props.inputData !== null && pageInfo.value.attrs.isCopyInputData) {
					inputCopy = JSON.parse(JSON.stringify(props.inputData));
				}
				// 合并设置默认值和输入参数, 如果默认值和输入参数都存在某个key，则用输入值替换默认值
				let dialogData = {};
				console.log('attrsattrsattrs', attrs);
				if (attrs['dialog-data']) {
					dialogData = attrs['dialog-data'];
				}
				Object.assign(pageData.value, { ...dialogData, ...inputCopy });
				for (const key in pageData.value) {
					if (pageData.value[key] === '' && dialogData[key]) {
						pageData.value[key] = dialogData[key];
					}
				}
				globalData.value = pageInfo.value.others.globelParams || null;
				if (pageInfo.value.others.ifRefresh) {
					await handleRefreshCurr();
				}
				isReady.value = true;
			}
		}

		// 如果刷新，调用事件
		const handleRefreshCurr = async () => {
			const { actions } = pageInfo.value.others;
			const that = { ...props, ...state };
			const controller = new Controller({}, actions, that);
			await controller.run(getDataMgr());
		};

		const getDataMgr = () => {
			const globelParams = { ...toRefs(globalData), ...toRefs(pageInfo.value?.others.globelParams) };
			return new Datar(pageData.value, props.inputData, globelParams);
		};

		const clear = () => {
			localforage
				.clear()
				.then(function () {
					// 当数据库被全部删除后，此处代码运行
					console.log('Database is now empty.');
				})
				.catch(function (err) {
					// 当出错时，此处代码运行
					console.log(err);
				});
		};
		const setFormData = (val: any, cpn: Record<string, any>) => {
			pageData.value[cpn.vModel] = val;
		};
		const clone = () => {
			console.log('customizePage clone');
			ctx.emit('clone');
		};

		const updateFormData = (obj: any) => {
			pageData.value = JSON.parse(JSON.stringify(obj));
		};

		const handleOpenDialog = (cfg: any, data: any) => {
			dialogConfig.value = {
				title: cfg.title,
				fieldDefines: [],
				submitUrl: cfg.pageid,
				width: 'auto',
				opType: 5,
				ot: cfg.type === '0' ? 2 : 3,
				formData: data,
			};
			dialogVisible.value = true;
			console.log('handleOpenDialog', dialogVisible.value);
		};

		const copyPageParams = computed(() => {
			return {
				...JSON.parse(JSON.stringify(props.inputData)),
				...JSON.parse(JSON.stringify(pageData.value)),
				...JSON.parse(JSON.stringify(globalData.value)),
			};
		});

		const handleCloseDialog = (data: Record<string, any>) => {
			ctx.emit('handleEmitEvent', 'handleCloseDialog', data);
		};

		const handleRefreshEmit = () => {
			handleEmitEvent('handleRefreshEmit', {});
		};
		const handleExportData = (data: Record<string, any>) => {
			console.log('handleExportData', data);
			handleEmitEvent('handleExportDataEmit', data);
		};
		const handleEmitEvent = (name: string, item: Record<string, any>, rowIndex = -1) => {
			const datar = getDataMgr();

			if (['handleClick'].includes(name)) {
				console.log('[Debug][CustomPage]botton event: ', datar);
				const { list, cfg } = item.actions;
				cfg.FieldID = item.FieldID || null;
				const controller = new Controller(cfg, list, proxy, collectedUp as any);
				console.log('proxy:', proxy);
				controller.run(datar, -1);
			} else if (['handleSizeChange', 'handleCurrentChange', 'handleRefreshCurr'].includes(name)) {
				const { actions } = pageInfo.value.others;
				const controller = new Controller({}, actions, proxy);
				controller.run(datar);
			} else if (['handleTableClick'].includes(name)) {
				const { actions, actionsCfg } = item;

				const controller = new Controller(actionsCfg, actions, proxy);
				controller.run(datar, rowIndex);
			} else if (['handleRefreshEmit'].includes(name)) {
				ctx.emit('handleEmitEvent', 'handleRefreshCurr');
			} else if (['sendEmitAction'].includes(name)) {
				// 提交给上级的事件
				ctx.emit('handleEmitEvent', 'sendEmitAction', item, props.pageid);
			} else if (['recieveEmitAction'].includes(name)) {
				// 接收处理下级提交的事件
				const controller = new Controller({}, [item], proxy);
				controller.run(datar);
			} else if (['handleCloseDialog'].includes(name)) {
				console.log('handleEmitEventhandleEmitEvent', dialogVisible.value);
				dialogVisible.value = false;
				console.log('handleEmitEventhandleEmitEvent', dialogVisible.value);
			} else if (['uploadCollect'].includes(name)) {
				collectedUp.value.push(item);
			} else if (['handleExportDataEmit'].includes(name)) {
				ctx.emit('handleEmitEvent', 'handleExportData', item);
			} else if (['handleExportData'].includes(name)) {
				pageData.value = { ...pageData.value, ...item };
				console.log('handleEmitEvent handleExportData', { item, pageData });
			}
		};

		return {
			state,
			...toRefs(props),
			dialogConfig,
			setFormData,
			clone,
			updateFormData,
			handleEmitEvent,
			clear,
			handleOpenDialog,
			handleCloseDialog,
			copyPageParams,
			handleRefreshCurr,
			handleRefreshEmit,
			handleExportData,
			formRef,
		};
	},
});
</script>
